#include <iostream>
#include <pthread.h>
#include <unistd.h>

int cnt = 10;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_c1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_c2 = PTHREAD_COND_INITIALIZER;

void *handler_c1(void *)
{
    while (true)
    {
        pthread_mutex_lock(&mutex);

        if (cnt == 0)
        {
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&cond_c1);
            break;
        }
        while (cnt % 2 == 1)
        {
            pthread_cond_wait(&cond_c1, &mutex);
        }
        std::cout << "thread 1 get number" << cnt << std::endl;
        cnt--;
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond_c2);
        sleep(1);
    }
}

void *handler_c2(void *)
{
    while (true)
    {
        pthread_mutex_lock(&mutex);

        if (cnt == 0)
        {
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&cond_c1);
            break;
        }
        while (cnt % 2 == 0)
        {
            pthread_cond_wait(&cond_c2, &mutex);
        }
        std::cout << "thread 2 get number" << cnt << std::endl;
        cnt--;
        pthread_mutex_unlock(&mutex);

        pthread_cond_signal(&cond_c1);
        sleep(1);
    }
}

int main()
{
    pthread_t c1, c2;

    pthread_create(&c1, nullptr, handler_c1, nullptr);
    pthread_create(&c2, nullptr, handler_c2, nullptr);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);

    return 0;
}